﻿using RFIDSystem.DAL;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace RFIDSystem
{

    
    public partial class ProductCatalog : BaseForm
    {
        

        public ProductCatalog()
        {
            InitializeComponent();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if(txtProductCatalogCode.Text=="" || txtProductCatalogName.Text=="")
            {
                MessageBox.Show("请输入分类编码与分类名称");
                return;
            }
                       
            product_catalog productCatalog = new product_catalog();
            productCatalog.product_catalog_code = txtProductCatalogCode.Text;
            productCatalog.product_catalog_name = txtProductCatalogName.Text;
            productCatalog.create_datetime = DateTime.Now;
            DAL.product_catalog.Add(productCatalog);
            DAL.SaveChanges();
            BindList();
        }

        private void BindList()
        {
            dataGridView1.AutoGenerateColumns = false;
            dataGridView1.DataSource = DAL.product_catalog.ToList();
        }

        private void ProductCatalog_Load(object sender, EventArgs e)
        {
            BindList();
        }

        private void dataGridView1_SelectionChanged(object sender, EventArgs e)
        {
            txtProductCatalogCode.Text = (string)dataGridView1.CurrentRow.Cells[1].Value;
            txtProductCatalogName.Text = (string)dataGridView1.CurrentRow.Cells[2].Value;
        }

        private void btnModify_Click(object sender, EventArgs e)
        {
            if (txtProductCatalogCode.Text == "" || txtProductCatalogName.Text == "")
            {
                MessageBox.Show("请输入分类编码与分类名称");
                return;
            }

            int currentId = (int)dataGridView1.CurrentRow.Cells[0].Value;
            var productCatalog = DAL.product_catalog.Where(
                 (p) => p.product_catalog_id == currentId
             ).FirstOrDefault();
            
            productCatalog.product_catalog_code = txtProductCatalogCode.Text;
            productCatalog.product_catalog_name = txtProductCatalogName.Text;
            productCatalog.create_datetime = DateTime.Now;
            DAL.SaveChanges();
            BindList();
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            int currentId = (int)dataGridView1.CurrentRow.Cells[0].Value;
            var productCatalog = DAL.product_catalog.Find(currentId);

            if(productCatalog.product_product.Count>0)
            {
                MessageBox.Show("该产品类别下已经存在产品，不能删除");
                return;
            }

            DAL.product_catalog.Remove(productCatalog);
            DAL.SaveChanges();
            BindList();
        }
    }
}
